import React, {Component} from 'react'
import {connect} from 'react-redux';
import {getSideList,addTab} from '../../redux/main.redux'
import Loading from '../../common/Loading/Loading'
import Config from '../../config'
import './NavMenu.scss';
import {Link, withRouter} from 'react-router-dom';
import {Menu,Layout} from 'antd';
const { Sider } = Layout;
const SubMenu = Menu.SubMenu;

@withRouter
@connect(state => state.navsidelist || {}, {getSideList,addTab})
class NavMenu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      openKeys: [],
      defaultKeys: ['101','1011'],
      colres: true
    }
    this.handleMenuClick = this.handleMenuClick.bind(this)
  }


  componentDidMount() {
    this.props.getSideList();
    let hisToryPath = this.props.history.location.pathname;
    if(hisToryPath === '/' || hisToryPath !== '/') {
      this.props.history.push('/main')
      setTimeout(() => {
        let item = {'key': '/main',isOpen:true,url: hisToryPath, title: '工作台'}
        this.props.getlistLen(this.props.navlist.length)
        // 异步this.props有时候会没有获取到数据
        if(this.props.navlist.length > 0) {
          this._forAddTab(this.props.navlist, item)
        }
      },100)
    }
  }

  onOpenChange = (openKeys) => {
    const rootSubmenuKeys = [];
    const {navlist} = this.props;
    navlist.map((v,index) => {
     return  v.child ?  rootSubmenuKeys.push(v.child) : null
    })
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  }
  
  handleMenuClick(item) {
    const {navlist} = this.props;
    item.isOpen = true;
    this._forAddTab(navlist,item)
    // 一级菜单
    if (item.keyPath.length === 1) {
      this.setState({
        openKeys: []
      })
    } 
  }

  _forAddTab(navlist,item) {
    this._forTemplate(navlist,item)
  }
  _forTemplate(objectD,item) {
      let title = '';
      let key = '';
      let _retUrl = '';
      let icon = '';
      if(objectD.length > 0) {
        objectD.forEach((obj,i) => {
          if(obj.child) {
            obj.children.forEach(v => {
              if (item.key === v.url) {
                return (title = v.name, key = v.url, _retUrl=v.url,icon=v.icon,this.props.addTab({title,key,url:_retUrl,icon,isOpen: item.isOpen}))
              } else if(v.child){
                this._forTemplate([v],item)
              }
            })
          }
          if(obj.url === item.key) {
            return (title = obj.name, key = obj.url, _retUrl=obj.url,icon=obj.icon,this.props.addTab({title,key,url:_retUrl,icon,isOpen: item.isOpen}))
          }
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      colres: nextProps.collapsed
    })
    if(nextProps.panes.length>0) {
      this._retProps(nextProps)
    }
  }

  _retProps(params) {
    params.navlist.forEach(v => {
      params.panes.forEach(q => {
        if(v.url === q.key && q.isOpen) {
          this.setState({
            openKeys: []
          })
        } else if(v.children){
          this._retchild(v.children,q)
        }
      })
    })
  }
_retchild(objectDB,q,par) {
  if(objectDB) {
    objectDB.forEach(xx => {
      if(xx.child) {
        this._retchild(xx.children,q,xx.par)
      }
      if(xx.url === q.key && q.isOpen) {
        if(par) {
          this.setState({
            openKeys: [par,xx.par]
          })
          return
        } 
        this.setState({
          openKeys: [xx.par]
        })
      }
    })
  }
  }
 

  formSubmenusChild(obj){
    let cHtml=<div></div>;
    let childArray=obj.children;
    if(void 0 !== typeof(childArray) && childArray && childArray.length > 0) {
      cHtml = childArray.map((item, i) => {
            return this.formSubmenusChild(item);
        });
        return <SubMenu key={obj.url || obj.child} title={<span className="anticon"><i className={`fa fa-icon-left-menu fa-${obj.icon}`} aria-hidden="true"></i><span>{obj.name}</span></span>}>{cHtml}</SubMenu>
    }else{
        return <Menu.Item routeurl={obj.url} key={obj.url}><Link to={obj.url}><span className="anticon"><i className={`fa fa-icon-left-menu fa-${obj.icon}`} aria-hidden="true"></i></span><span className="nav-text">{obj.name}</span></Link></Menu.Item>
    }
  }

  render() {
    const {navlist,panes} = this.props;
    if(navlist.length > 0) {
        var html = navlist.map((obj,i)=> {
          if (void 0 !== typeof(obj.child) && obj.children && obj.children.length > 0) {
              return this.formSubmenusChild(obj);
          } else {
            //这里的routeurl是路由地址，是自定义的一个属性
            return (<Menu.Item routeurl={obj.url} key={obj.url}><Link data-par={obj.url} to={obj.url}><span className="anticon"><i className={`fa fa-icon-left-menu fa-${obj.icon}`} aria-hidden="true"></i></span><span className="nav-text">{obj.name}</span></Link></Menu.Item>)
          }
      });
    }
    return (
      <Sider
        width={290}
        breakpoint="md"
        collapsedWidth={80}
        className={`app-sider-container`}
        collapsed={this.state.colres}
      >
        <div className="logo">
          <img src={require('../../static/mdedia/logo.png')} alt="logo" />
          <h1>{Config.shortProjectName}</h1>
        </div>
        {
          !navlist || panes.length <= 0 ? <Loading tip="左侧菜单正在加载..." delay={1000} size="large" /> 
          : 
          <Menu
            theme="dark"
            style={{
              margin: '16px 0',
              width: '100%'
            }}
            onOpenChange={this.onOpenChange}
            onClick={this.handleMenuClick}
            mode="inline"
            openKeys={this.state.openKeys}
            selectedKeys={panes.map(v => v.isOpen ? v.url : null)}
            defaultSelectedKeys={panes.map(v => v.isOpen ? v.key : null)}>
            {
              html
            }
          </Menu>
        }
      </Sider>
    )
  }
}
export default NavMenu
